package com.shuorikeji.huohuo.ui.home;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.ReadBgAdapter;
import com.shuorikeji.huohuo.adapter.ReadFontAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.BaseCallBackBean;
import com.shuorikeji.huohuo.bean.BookDetailInfoSubBean;
import com.shuorikeji.huohuo.bean.BookDetailMainBean;
import com.shuorikeji.huohuo.bean.BookZjDetailMainBean;
import com.shuorikeji.huohuo.bean.BookZjDetailSubBean;
import com.shuorikeji.huohuo.bean.FontBgInfoBean;
import com.shuorikeji.huohuo.bean.FontBgMainBean;
import com.shuorikeji.huohuo.bean.FontLocalInfoBean;
import com.shuorikeji.huohuo.bean.JbTypeBean;
import com.shuorikeji.huohuo.bean.ReadBookConfigBean;
import com.shuorikeji.huohuo.bean.UserInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.DialogUtil;
import com.shuorikeji.huohuo.utils.FontDownloader;
import com.shuorikeji.huohuo.utils.FontManager;
import com.shuorikeji.huohuo.utils.JsonUtil;
import com.shuorikeji.huohuo.utils.PreUtils;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class ReadBookTempActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.tv_show)
    TextView tvShow;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_back_2)
    ImageView ivBack2;
    @BindView(R.id.ll_title_1)
    LinearLayout llTopTitle1;
    @BindView(R.id.ll_title_2)
    LinearLayout llTopTitle2;
    @BindView(R.id.tv_zj_info)
    TextView tvZjInfo;
    @BindView(R.id.ll_add_sj)
    LinearLayout llAddSj;
    @BindView(R.id.iv_add_sj)
    ImageView ivAddSj;
    @BindView(R.id.tv_add_sj)
    TextView tvAddSj;
    @BindView(R.id.ll_pl)
    LinearLayout llPl;
    @BindView(R.id.tv_pl_count)
    TextView tvPlCount;
    @BindView(R.id.ll_more)
    LinearLayout llMore;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.ll_bottom_1)
    LinearLayout llBottom1;
    @BindView(R.id.rv_bg)
    RecyclerView rvBg;
    @BindView(R.id.sb_light)
    SeekBar sbLight;
    @BindView(R.id.ll_h_eye_mode)
    LinearLayout llHeyeMode;
    @BindView(R.id.ll_bottom_2)
    LinearLayout llBottom2;
    @BindView(R.id.ll_ml)
    LinearLayout llMl;
    @BindView(R.id.ll_light)
    LinearLayout llLight;
    @BindView(R.id.ll_night_mode)
    LinearLayout llNightMode;
    @BindView(R.id.ll_set)
    LinearLayout llSet;
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.iv_h_eye)
    ImageView ivHeye;
    @BindView(R.id.ll_bottom_3)
    LinearLayout llBottom3;
    @BindView(R.id.tv_sx_font)
    TextView tvSxFont;
    @BindView(R.id.tv_zj_font)
    TextView tvZjFont;
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.tv_fy_type_1)
    TextView tvFyType1;
    @BindView(R.id.tv_fy_type_2)
    TextView tvFyType2;
    @BindView(R.id.tv_fy_type_default)
    TextView tvFyTypeDefault;
    @BindView(R.id.tv_before_zj)
    TextView tvBeforeZj;
    @BindView(R.id.sb_zj_jd)
    SeekBar sbZjJd;
    @BindView(R.id.tv_next_zj)
    TextView tvNextZj;
    @BindView(R.id.ll_bottom_4)
    LinearLayout llBottom4;
    @BindView(R.id.ll_fy_type)
    LinearLayout llFyType;//翻页类型
    @BindView(R.id.ll_line_space_4)
    LinearLayout llLineSpace4;
    @BindView(R.id.ll_line_space_3)
    LinearLayout llLineSpace3;
    @BindView(R.id.ll_line_space_2)
    LinearLayout llLineSpace2;
    @BindView(R.id.rv_font)
    RecyclerView rvFont;

    private int BOOK_ID;
    private int ZJ_ID;
    private BookDetailInfoSubBean bookInfoDta;
    private BookZjDetailSubBean zjDetailInfoBean;
    private int plCount;
    private TextPaint textPaint;
    private StaticLayout staticLayout;
    private List<String> zjFyContent = new ArrayList<>();
    private int curReadContentIndex;
    private float x1, x2;
    private ReadBgAdapter readBgAdapter;
    private List<FontBgInfoBean> readBgList = new ArrayList<>();
    private List<FontBgInfoBean> readFontList = new ArrayList<>();
    private ReadFontAdapter readFontAdapter;
    private UserInfoBean userInfo;
    private PopupWindow morePop;
    private Dialog jbDialog;
    private List<JbTypeBean> jbTypelist = new ArrayList<>();
    private int hEYEMode = 1;//护眼模式 1未开启；2开启
    private int nightMode = 1;//夜间模式 1未开启；2开启
    private ReadBookConfigBean readBookConfig;
    private int curFontSize;
    private int txtShowHeight;
    private int TOTAL_ZJ_COUNT;
    private List<String> fyTypeList = new ArrayList<>();
    private Dialog shareDialog;
    private FontBgInfoBean fontBean;
    private Typeface typeface;
    private Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    typeface = (Typeface) msg.obj;
                    try {
                        if (typeface != null) {
                            llBottom3.setVisibility(View.GONE);
                            tvShow.setTypeface(typeface);
                            setContentShow();
                            setFont(fontBean.getId());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("wxl", e.getMessage());
                    }
                    break;
                case 2:
                    readFontAdapter.setData(readFontList);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        txtShowHeight = llMain.getMeasuredHeight() - viewTop.getMeasuredHeight() - llTopTitle1.getMeasuredHeight() - 300;
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_read_book_temp);
    }

    @Override
    protected void initData() {
        userInfo= BusinessUtils.getUserInfo();
        curFontSize = 16;
        setFyData();
        setViewShowState(1);
        initAdapter();
        getFontBg();
        initIntent();
        initClick();
    }

    /**
     * 翻页类型数据
     */
    private void setFyData() {
        fyTypeList.clear();
        fyTypeList.add("上下");
        fyTypeList.add("平移");
        fyTypeList.add("默认");
        showFyLayout();
    }

    private void showFyLayout() {
        llFyType.removeAllViews();
        for (int i = 0; i < fyTypeList.size(); i++) {
            View subView = View.inflate(ReadBookTempActivity.this, R.layout.fy_item_layout, null);
            subView.setPadding(0, 0, 40, 0);
            LinearLayout llMain = subView.findViewById(R.id.ll_main);
            TextView tvType = subView.findViewById(R.id.tv_type);
            tvType.setText(fyTypeList.get(i));
            llMain.setId(i);
            llFyType.addView(subView);
            llMain.setOnClickListener(view -> {
                llBottom3.setVisibility(View.GONE);
                if ("上下".equals(fyTypeList.get(llMain.getId()))) {
                    setReadConfig(1);
                } else if ("平移".equals(fyTypeList.get(llMain.getId()))) {
                    setReadConfig(2);
                } else if ("默认".equals(fyTypeList.get(llMain.getId()))) {
                    setReadConfig(3);
                }
            });
        }
    }

    /**
     * top及bottom布局显示状态
     *
     * @param flag 1 只显示top1
     *             2 只显示top2 bottom 2
     *             3 只显示bottom1 隐藏bottom3 bottom4 （其他不考虑）
     *             4 只显示bottom3 隐藏bottom1 bottom4（其他不考虑）
     *             5 只显示bottom4 隐藏bottom1 bottom3（其他不考虑）
     */
    private void setViewShowState(int flag) {
        if (flag == 1) {
            llTopTitle1.setVisibility(View.VISIBLE);
            llTopTitle2.setVisibility(View.GONE);
            llBottom1.setVisibility(View.GONE);
            llBottom2.setVisibility(View.GONE);
            llBottom3.setVisibility(View.GONE);
            llBottom4.setVisibility(View.GONE);
        } else if (flag == 2) {
            llTopTitle1.setVisibility(View.GONE);
            llTopTitle2.setVisibility(View.VISIBLE);
            llBottom2.setVisibility(View.VISIBLE);
        } else if (flag == 3) {
            llBottom1.setVisibility(View.VISIBLE);
            llBottom3.setVisibility(View.GONE);
            llBottom4.setVisibility(View.GONE);
        } else if (flag == 4) {
            llBottom1.setVisibility(View.GONE);
            llBottom3.setVisibility(View.VISIBLE);
            llBottom4.setVisibility(View.GONE);
        } else if (flag == 5) {
            llBottom1.setVisibility(View.GONE);
            llBottom3.setVisibility(View.GONE);
            if (llBottom4.getVisibility() == View.VISIBLE) {
                llBottom4.setVisibility(View.GONE);
            } else {
                llBottom4.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setTextPaint(int textSize) {
        textPaint = new TextPaint();
        textPaint.setColor(Color.BLACK);
        try {
            if (typeface != null) {
                textPaint.setTypeface(typeface);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        textPaint.setTextSize(textSize);
        textPaint.setAntiAlias(true);
    }

    private void initAdapter() {
        rvBg.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false));
        if (rvBg.getItemDecorationCount() == 0) {
            rvBg.addItemDecoration(new GridDividerItemDecoration(20));
        }
        readBgAdapter = new ReadBgAdapter(mContext, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        FontBgInfoBean bgBean = (FontBgInfoBean) object;
                        setReadBg(bgBean.getId());
                        BusinessUtils.setLoadImgForLayout(ReadBookTempActivity.this,
                                Constant.IMG_OSS_BASE_URL + bgBean.getBackdrop_image(), llMain);
                        break;
                }
            }
        });
        rvBg.setAdapter(readBgAdapter);

        rvFont.setLayoutManager(new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false));
        if (rvFont.getItemDecorationCount() == 0) {
            rvFont.addItemDecoration(new GridDividerItemDecoration(20));
        }
        readFontAdapter = new ReadFontAdapter(mContext, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        fontBean = (FontBgInfoBean) object;
                        if ("系统字体".equals(fontBean.getName())) {
                            PreUtils.put(Constant.CUR_FONT, "");
                            llBottom3.setVisibility(View.GONE);
                            typeface = Typeface.DEFAULT;
                            tvShow.setTypeface(typeface);
                            setContentShow();
                        } else {
                            xgFontsState(1);
                            downloadOnlineFont(fontBean.getName(), Constant.IMG_OSS_BASE_URL + fontBean.getFont_file());
                        }
                        break;
                }
            }
        });
        rvFont.setAdapter(readFontAdapter);
    }

    private void initIntent() {
        Intent intent = getIntent();
        BOOK_ID = intent.getIntExtra("BOOK_ID", -1);
        ZJ_ID = intent.getIntExtra("ZJ_ID", -1);
        plCount = intent.getIntExtra("PL_COUNT", 0);
        TOTAL_ZJ_COUNT = intent.getIntExtra("TOTAL_ZJ_COUNT", 0);
        tvPlCount.setText(String.valueOf(plCount));
        getBookDetail();
    }

    public void getTxtPages(CharSequence text, TextPaint paint, int pageWidth, int pageHeight, float lineSpace, float spaceAdd) {
        zjFyContent.clear();
        // 计算每页可以显示的行数
        int lineHeight = (int) (paint.getFontMetrics().bottom - paint.getFontMetrics().top + lineSpace);
        int linesPerPage = pageHeight / lineHeight;
        if (staticLayout != null) {
            staticLayout = null;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            staticLayout = StaticLayout.Builder.obtain(text, 0, text.length(), paint, pageWidth)
                    .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                    .setLineSpacing(lineSpace, spaceAdd) // 明确设置行间距
                    .setIncludePad(true)
                    .build();
        } else {
            staticLayout = new StaticLayout(
                    text,
                    paint,
                    pageWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    lineSpace,
                    spaceAdd,
                    true);
        }
        int lineCount = staticLayout.getLineCount();
        int startLine = 0;
        while (startLine < lineCount) {
            int endLine = Math.min(startLine + linesPerPage, lineCount);
            int start = staticLayout.getLineStart(startLine);
            int end = staticLayout.getLineEnd(endLine - 1);
            zjFyContent.add(text.subSequence(start, end).toString());
            startLine = endLine;
        }
        if (zjFyContent != null && zjFyContent.size() > 0) {
            tvShow.setText(zjFyContent.get(curReadContentIndex));
        }
    }

    /**
     * 更新字体下载状态
     *
     * @param flag 1开始下载字体
     *             2下载字体完成或失败
     */
    private void xgFontsState(int flag) {
        if (readFontList != null && readFontList.size() > 0 && fontBean != null) {
            for (int i = 0; i < readFontList.size(); i++) {
                if (flag == 1) {
                    if (fontBean.getId() == readFontList.get(i).getId()) {
                        readFontList.get(i).setDowning(true);
                    } else {
                        readFontList.get(i).setDowning(false);
                    }
                } else {
                    readFontList.get(i).setDowning(false);
                }
            }
        }
    }

    /**
     * 下载在线字体
     */
    private void downloadOnlineFont(String name, String url) {
        if (url.endsWith(".otf") || url.endsWith(".ttf")) {
            FontDownloader.downloadFont(ReadBookTempActivity.this, url, new FontDownloader.FontDownloadCallback() {
                @Override
                public void onSuccess(File fontFile) {
                    xgFontsState(2);
                    mHandler.sendEmptyMessage(2);
                    FontLocalInfoBean data = new FontLocalInfoBean();
                    data.setOnlineFont(false);
                    data.setFontName(name);
                    data.setFontPath(fontFile.getAbsolutePath());
                    setReadFont(data);
                }

                @Override
                public void onProgress(int progress) {
                    mHandler.sendEmptyMessage(2);
                }

                @Override
                public void onFailure(String error) {
                    Log.e("wxl", "下载字体失败：" + error);
                    xgFontsState(2);
                    mHandler.sendEmptyMessage(2);
                }
            });
        } else {
            ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "字体格式错误");
        }
    }

    /**
     * 设置显示字体
     */
    private void setReadFont(FontLocalInfoBean data) {
        switch (data.getFontPath()) {
            case "default":
                typeface = Typeface.DEFAULT;
                break;
            case "serif":
                typeface = Typeface.SERIF;
                break;
            case "sans-serif":
                typeface = Typeface.SANS_SERIF;
                break;
            default:
                PreUtils.put(Constant.CUR_FONT, data.getFontPath());
                typeface = FontManager.getTypeface(mContext, data.getFontPath());
        }
        try {
            Message message = Message.obtain();
            message.obj = typeface;
            message.what = 1;
            mHandler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getFontBg() {
        mPresenter.getFontBg(ReadBookTempActivity.this, false, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        FontBgMainBean data = (FontBgMainBean) object;
                        readBgList.clear();
                        readFontList.clear();
                        readBgList.addAll(data.getData().getBack());

                        FontBgInfoBean systemFontBean = new FontBgInfoBean();
                        systemFontBean.setName("系统字体");
                        readFontList.add(systemFontBean);
                        systemFontBean = null;
                        readFontList.addAll(data.getData().getFont());
                        readBgAdapter.setData(readBgList);
                        readFontAdapter.setData(readFontList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void setReadBg(int id) {
        mPresenter.setReadBg(ReadBookTempActivity.this, id, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void setFont(int id) {
        mPresenter.setFont(ReadBookTempActivity.this, id, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getBookDetail() {
        mPresenter.getBookDetail(ReadBookTempActivity.this, BOOK_ID, false, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        BookDetailMainBean data = (BookDetailMainBean) object;
                        bookInfoDta = data.getData();
                        if (bookInfoDta != null) {
                            ivAddSj.setImageResource((bookInfoDta.getBookshelf() == 1) ? R.mipmap.icon_book_detail_y_add_sj : R.mipmap.icon_book_detail_add_sj);
                            tvAddSj.setText((bookInfoDta.getBookshelf() == 1) ? "已接入书架" : "加入书架");
                            tvAddSj.setTextColor((bookInfoDta.getBookshelf() == 1) ? getResources().getColor(R.color.color_BBBBBB)
                                    : getResources().getColor(R.color.color_333333));
                        }
                        getBookZjDetail(true);
                        //getBookPl();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getBookZjDetail(boolean show) {
        mPresenter.getBookZjDetail(ReadBookTempActivity.this, BOOK_ID, ZJ_ID, show, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        BookZjDetailMainBean data = (BookZjDetailMainBean) object;
                        zjDetailInfoBean = data.getData();
                        curReadContentIndex = 0;
                        if (zjDetailInfoBean != null) {
                            setContentShow();
                            if (bookInfoDta != null) {
                                bookInfoDta.setChapter_num(zjDetailInfoBean.getChapter().getChapter_number());
                                bookInfoDta.setCurZjTitle(zjDetailInfoBean.getChapter().getTitle());
                                bookInfoDta.setZjId(ZJ_ID);
                                PreUtils.put(Constant.CUR_READING_BOOK_ZJ, JsonUtil.toJson(bookInfoDta));
                            }
                            BigDecimal bigDecimal = BusinessUtils.divBigDecimal(new BigDecimal(zjDetailInfoBean.getChapter().getChapter_number())
                                    , new BigDecimal(TOTAL_ZJ_COUNT), 2, false);
                            sbZjJd.setProgress(BusinessUtils.mul(bigDecimal, new BigDecimal(100), 0).intValue());
                            tvZjInfo.setText(zjDetailInfoBean.getChapter().getChapter_number() + " " + zjDetailInfoBean.getChapter().getTitle());
                            addReadHis(zjDetailInfoBean.getChapter().getNovel_id());
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void addReadHis(int bookId) {
        mPresenter.addReadHis(ReadBookTempActivity.this, ZJ_ID, bookId, 1, false, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                }
            }
        });
    }

    private void addSj(int novelId) {
        mPresenter.addSj(ReadBookTempActivity.this, novelId, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "已加入书架");
                        bookInfoDta.setBookshelf(1);
                        ivAddSj.setImageResource((bookInfoDta.getBookshelf() == 1) ? R.mipmap.icon_book_detail_y_add_sj : R.mipmap.icon_book_detail_add_sj);
                        tvAddSj.setText((bookInfoDta.getBookshelf() == 1) ? "已加入书架" : "加入书架");
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void showMorePop(TextView tvMore) {
        if (morePop != null) {
            if (morePop.isShowing()) {
                morePop.dismiss();
            }
            morePop = null;
        }
        View contentView = LayoutInflater.from(ReadBookTempActivity.this).inflate(R.layout.pop_read_book_more_layout, null);
        morePop = new PopupWindow(contentView);
        LinearLayout llShare = contentView.findViewById(R.id.ll_share);
        LinearLayout llGoLib = contentView.findViewById(R.id.ll_go_lib);
        LinearLayout llBookDetail = contentView.findViewById(R.id.ll_book_detail);
        LinearLayout llOpenVip = contentView.findViewById(R.id.ll_open_vip);
        LinearLayout llJb = contentView.findViewById(R.id.ll_jb);
        llShare.setOnClickListener(view -> {
            showShareDialog();
            morePop.dismiss();
        });
        llGoLib.setOnClickListener(view -> {
//            Intent intent = new Intent(ReadBookTempActivity.this, LibActivity.class);
//            startActivity(intent);
            morePop.dismiss();
        });
        llBookDetail.setOnClickListener(view -> {
            Intent intent = new Intent(ReadBookTempActivity.this, BookDetailActivity.class);
            intent.putExtra("BOOK_ID", BOOK_ID);
            startActivity(intent);
            morePop.dismiss();
        });
        llOpenVip.setOnClickListener(view -> {

        });
        llJb.setOnClickListener(view -> {
            setJbTypeData();
            showJbDialog();
            morePop.dismiss();
        });
        morePop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        morePop.setWidth(500);
        morePop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        morePop.setOutsideTouchable(true);
        morePop.setFocusable(true);
        morePop.setContentView(contentView);
        morePop.showAsDropDown(tvMore, 0, 0);
    }

    private void showShareDialog() {
        shareDialog = DialogUtil.showShareDialog(ReadBookTempActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        //QQ收藏
                        break;
                    case 2:
                        //微信好友
                        break;
                    case 3:
                        //微信收藏
                        break;
                }
            }
        });
    }

    private void setJbTypeData() {
        jbTypelist.clear();

        JbTypeBean data1 = new JbTypeBean();
        data1.setSec(true);
        data1.setType("低俗色情");
        jbTypelist.add(data1);
        data1 = null;

        JbTypeBean data2 = new JbTypeBean();
        data2.setSec(false);
        data2.setType("内容敏感");
        jbTypelist.add(data2);
        data2 = null;

        JbTypeBean data3 = new JbTypeBean();
        data3.setSec(false);
        data3.setType("血腥暴力");
        jbTypelist.add(data3);
        data3 = null;

        JbTypeBean data4 = new JbTypeBean();
        data4.setSec(false);
        data4.setType("赌博");
        jbTypelist.add(data4);
        data4 = null;

        JbTypeBean data5 = new JbTypeBean();
        data5.setSec(false);
        data5.setType("抄袭/侵权");
        jbTypelist.add(data5);
        data5 = null;

        JbTypeBean data6 = new JbTypeBean();
        data6.setSec(false);
        data6.setType("虐待未成年人");
        jbTypelist.add(data6);
        data6 = null;

        JbTypeBean data7 = new JbTypeBean();
        data7.setSec(false);
        data7.setType("其他问题");
        jbTypelist.add(data7);
        data7 = null;
    }

    private void showJbDialog() {
        jbDialog = DialogUtil.showJb(ReadBookTempActivity.this, jbTypelist, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        BaseCallBackBean data = (BaseCallBackBean) object;
                        jbBook(data);
                        break;
                }
            }
        });
    }

    /**
     * 举报书籍章节
     *
     * @param data 数据
     */
    private void jbBook(BaseCallBackBean data) {
        mPresenter.jbBookZj(ReadBookTempActivity.this, data.getJbType(), data.getJbContent(), ZJ_ID, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "已举报");
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 设置当前 Activity 的屏幕亮度（无需权限）
     *
     * @param brightness 亮度值，范围为 0.0f（最暗）到 1.0f（最亮）
     */
    private void setScreenLight(float brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.screenBrightness = brightness;
        window.setAttributes(layoutParams);
    }

    /**
     * 根据配置设置夜间模式
     */
    private void setNightModeBg() {
        if (nightMode == 1) {
            nightMode = 2;
            llMain.setBackgroundColor(getResources().getColor(R.color.color_666F73));
        } else {
            nightMode = 1;
            llMain.setBackgroundColor(getResources().getColor(R.color.color_F6F6F6));
        }
    }

    /**
     * 设置行间距
     *
     * @param flag 行间距 1：四行 2：三行 3：二行
     */
    private void setLineSpaceConfig(int flag) {
        llBottom3.setVisibility(View.GONE);
        if (readBookConfig == null) {
            readBookConfig = new ReadBookConfigBean();
        }
        readBookConfig.setLineSpace(flag);
        PreUtils.put(Constant.READ_BOOK_CONFIG, JsonUtil.toJson(readBookConfig));
        setContentShow();
    }

    private void initClick() {
        ivBack.setOnClickListener(view -> {
            finish();
        });
        ivBack2.setOnClickListener(view -> {
            finish();
        });
        llLineSpace2.setOnClickListener(view -> {
            setLineSpaceConfig(3);
        });
        llLineSpace3.setOnClickListener(view -> {
            setLineSpaceConfig(2);
        });
        llLineSpace4.setOnClickListener(view -> {
            setLineSpaceConfig(1);
        });
        llAddSj.setOnClickListener(view -> {
            //加入书架
            if (bookInfoDta != null) {
                if (bookInfoDta.getBookshelf() == 0) {
                    addSj(BOOK_ID);
                }
            }
        });
        llPl.setOnClickListener(view -> {
            //查看评论
            if (bookInfoDta != null) {
                Intent intent = new Intent(ReadBookTempActivity.this, BookPlActivity.class);
                intent.putExtra("BOOK_INFO", JsonUtil.toJson(bookInfoDta));
                intent.putExtra("PL_COUNT", plCount);
                startActivity(intent);
            }
        });
        llMore.setOnClickListener(view -> {
            showMorePop(tvMore);
        });
        llMl.setOnClickListener(view -> {
            //目录
            //finish();
            setViewShowState(5);
        });
        llLight.setOnClickListener(view -> {
            //调节亮度
            setViewShowState(3);
        });
        sbLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                BigDecimal bigDecimal = BusinessUtils.divBigDecimal(new BigDecimal(i), new BigDecimal(10), 1, false);
                setScreenLight(bigDecimal.floatValue());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        llHeyeMode.setOnClickListener(view -> {
            //护眼模式
            if (hEYEMode == 1) {
                hEYEMode = 2;
                ivHeye.setImageResource(R.mipmap.icon_light_heye_open);
            } else {
                hEYEMode = 1;
                ivHeye.setImageResource(R.mipmap.icon_light_heye_close);
            }
            llMain.setBackgroundColor((hEYEMode == 1) ? getResources().getColor(R.color.color_F6F6F6)
                    : getResources().getColor(R.color.color_FBF1E6));
        });
        llNightMode.setOnClickListener(view -> {
            //夜间模式
            setNightModeBg();
        });
        llSet.setOnClickListener(view -> {
            //设置
            setViewShowState(4);
//            Intent intent = new Intent(ReadBookTempActivity.this, MoreSetActivity.class);
//            startActivityForResult(intent, 1001);
        });
        tvSxFont.setOnClickListener(view -> {
            curFontSize = curFontSize - 5;
            if (curFontSize <= 0) {
                curFontSize = 5;
            }
            setContentShow();
        });
        tvZjFont.setOnClickListener(view -> {
            curFontSize = curFontSize + 5;
            if (curFontSize > 50) {
                curFontSize = 50;
            }
            setContentShow();
        });
        tvFyType1.setOnClickListener(view -> {
            llBottom3.setVisibility(View.GONE);
            setReadConfig(1);
        });
        tvFyType2.setOnClickListener(view -> {
            llBottom3.setVisibility(View.GONE);
            setReadConfig(2);
        });
        tvFyTypeDefault.setOnClickListener(view -> {
            llBottom3.setVisibility(View.GONE);
            setReadConfig(3);
        });
        tvBeforeZj.setOnClickListener(view -> {
            if (zjDetailInfoBean != null) {
                if (!BusinessUtils.isEmpty(zjDetailInfoBean.getUp_chapter().getTitle())) {
                    ZJ_ID = zjDetailInfoBean.getUp_chapter().getId();
                    getBookZjDetail(true);
                } else {
                    ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "当前是第一章节");
                }
            }
        });
        tvNextZj.setOnClickListener(view -> {
            if (zjDetailInfoBean != null) {
                if (!BusinessUtils.isEmpty(zjDetailInfoBean.getNext_chapter().getTitle())) {
                    ZJ_ID = zjDetailInfoBean.getNext_chapter().getId();
                    getBookZjDetail(true);
                } else {
                    ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "当前是最后一章节");
                }
            }
        });
        tvShow.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        x1 = event.getX();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        x2 = event.getX();
                        if (x1 == x2) {
                            int pjArea = BusinessUtils.getDeviceWidth(ReadBookTempActivity.this) / 2;
                            if (x2 >= (pjArea - 100) && x2 <= (pjArea + 100)) {
                                //点击事件
                                if (llTopTitle1.getVisibility() == View.VISIBLE) {
                                    setViewShowState(2);
                                } else {
                                    setViewShowState(1);
                                }
                            } else {
                                if (x2 < (pjArea - 100)) {
                                    //上一章
                                    readBeforeZj();
                                    return true;
                                } else if (x2 > (pjArea + 100)) {
                                    //下一章
                                    readNextZj();
                                }
                            }
                        } else {
                            if (Math.abs(x1 - x2) <= 100) {
                                if (llTopTitle1.getVisibility() == View.VISIBLE) {
                                    setViewShowState(2);
                                } else {
                                    setViewShowState(1);
                                }
                            } else {
                                if (x1 - x2 > 100) {
                                    //左滑
                                    readNextZj();
                                    return true;
                                }
                                if (x2 - x1 > 100) {
                                    //右滑
                                    readBeforeZj();
                                    return true;
                                }
                            }
                        }
                        break;
                }
                return true;
            }
        });
        sbZjJd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true; // 拦截所有触摸事件
            }
        });
    }

    /**
     * 阅读上一章节
     */
    private void readBeforeZj() {
        curReadContentIndex = curReadContentIndex - 1;
        if (zjFyContent != null && zjFyContent.size() > 0) {
            if (curReadContentIndex >= 0) {
                tvShow.setText(zjFyContent.get(curReadContentIndex));
                startDh(2);
            } else {
                curReadContentIndex = 0;
                if (zjDetailInfoBean != null) {
                    if (!BusinessUtils.isEmpty(zjDetailInfoBean.getUp_chapter().getTitle())) {
                        ZJ_ID = zjDetailInfoBean.getUp_chapter().getId();
                        getBookZjDetail(true);
                    } else {
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "当前是第一章节");
                    }
                }
            }
        }
    }

    /**
     * 阅读下一章节
     */
    private void readNextZj() {
        curReadContentIndex = curReadContentIndex + 1;
        if (zjFyContent != null && zjFyContent.size() > 0) {
            if (curReadContentIndex < zjFyContent.size()) {
                tvShow.setText(zjFyContent.get(curReadContentIndex));
                startDh(1);
            } else {
                curReadContentIndex = zjFyContent.size() - 1;
                if (zjDetailInfoBean != null) {
                    if (!BusinessUtils.isEmpty(zjDetailInfoBean.getNext_chapter().getTitle())) {
                        ZJ_ID = zjDetailInfoBean.getNext_chapter().getId();
                        getBookZjDetail(true);
                    } else {
                        ToastShowUtil.showToastCenter(ReadBookTempActivity.this, "当前是最后一章节");
                    }
                }
            }
        }
    }

    /**
     * 设置阅读相关配置
     *
     * @param flag 1设置上下翻页
     *             2设置平移翻页
     *             3默认翻页
     */
    private void setReadConfig(int flag) {
        readBookConfig = BusinessUtils.getReadBookConfig();
        if (readBookConfig == null) {
            readBookConfig = new ReadBookConfigBean();

        }
        readBookConfig.setFyType(flag);
        PreUtils.put(Constant.READ_BOOK_CONFIG, JsonUtil.toJson(readBookConfig));
    }

    /**
     * 根据选择的设置显示文本内容
     */
    private void setContentShow() {
        readBookConfig = BusinessUtils.getReadBookConfig();
        if (readBookConfig == null) {
            readBookConfig = new ReadBookConfigBean();
        }
        tvShow.setTextSize(curFontSize);
        setTextPaint((int) tvShow.getTextSize());
        if (readBookConfig.getLineSpace() == 1) {
            //间距小
            tvShow.setLineSpacing(1, 1);
            String newContent = zjDetailInfoBean.getChapter().getContent().replace("\n", "");
            getTxtPages(Html.fromHtml(newContent), textPaint,
                    tvShow.getWidth() - tvShow.getPaddingLeft() - tvShow.getPaddingRight(), txtShowHeight, 1, 1);
        } else if (readBookConfig.getLineSpace() == 2) {
            tvShow.setLineSpacing(15, 1);
            String newContent = zjDetailInfoBean.getChapter().getContent().replace("\n", "");
            getTxtPages(Html.fromHtml(newContent), textPaint,
                    tvShow.getWidth() - tvShow.getPaddingLeft() - tvShow.getPaddingRight(), txtShowHeight, 15, 1);
        } else if (readBookConfig.getLineSpace() == 3) {
            tvShow.setLineSpacing(30, 1);
            String newContent = zjDetailInfoBean.getChapter().getContent().replace("\n", "");
            getTxtPages(Html.fromHtml(newContent), textPaint,
                    tvShow.getWidth() - tvShow.getPaddingLeft() - tvShow.getPaddingRight(), txtShowHeight, 30, 1);
        } else {
            tvShow.setLineSpacing(1, 1);
            String newContent = zjDetailInfoBean.getChapter().getContent().replace("\n", "");
            getTxtPages(Html.fromHtml(newContent), textPaint,
                    tvShow.getWidth() - tvShow.getPaddingLeft() - tvShow.getPaddingRight(), txtShowHeight, 1, 1);
        }
    }

    /**
     * @param flag 1左滑
     *             2右滑
     */
    public void startDh(int flag) {
        readBookConfig = BusinessUtils.getReadBookConfig();
        if (readBookConfig == null) {
            readBookConfig = new ReadBookConfigBean();
        }
        Animation animator = null;
        if (readBookConfig.getFyType() == 1) {
            if (flag == 1) {
                animator = AnimationUtils.loadAnimation(this, R.anim.pop_exit_anim);
            } else if (flag == 2) {
                animator = AnimationUtils.loadAnimation(this, R.anim.pop_enter_anim);
            }
            tvShow.startAnimation(animator);
        } else if (readBookConfig.getFyType() == 2) {
            if (flag == 1) {
                animator = AnimationUtils.loadAnimation(this, R.anim.slide_in_from_right);
            } else if (flag == 2) {
                animator = AnimationUtils.loadAnimation(this, R.anim.slide_in_from_left);
            }
            tvShow.startAnimation(animator);
        } else if (readBookConfig.getFyType() == 3) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1001:
                    setContentShow();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (morePop != null) {
            if (morePop.isShowing()) {
                morePop.dismiss();
            }
            morePop = null;
        }
        BusinessUtils.clearDialog(jbDialog);
        BusinessUtils.clearDialog(shareDialog);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}